import React from 'react';
import { Form, Input, Button, Card, message } from 'antd';
import { history } from 'umi';
import styles from './index.less';
import { auth } from '@/utils/auth';

interface LoginFormValues {
  username: string;
  password: string;
}

const LoginPage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = React.useState(false);

  const onFinish = async (values: LoginFormValues) => {
    try {
      setLoading(true);
      //const response = await fetch('/agentapi/auth/admin/login', {
        const response = await fetch('/agentapi/api/logins/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: values.username,
          password: values.password,
        }),
      });
      console.log(JSON.stringify({
        username: values.username,
        password: values.password,
      }));
      if (response.status === 401) {
        message.error('用户名或密码错误');
        return;
      }

      if (response.status === 201) {
        const data = await response.json();
        // 登录成功，保存token信息
        auth.setTokens({
          // accessToken: data.accessToken,
          refreshToken: data.refreshToken,
          // expiresIn: data.expiresIn,
          // userId: data.userId,
          username: values.username,
        });
        
        message.success('登录成功');
        history.push('/t_user_mange');
        return;
      }

      // 其他错误
      message.error('登录失败，请稍后重试');
      
    } catch (error) {
      console.error('Login error:', error);
      message.error('登录失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.container}>
      <Card title="AI分身管理系统" className={styles.card}>
        <Form
          form={form}
          name="login"
          onFinish={onFinish}
          autoComplete="off"
          layout="vertical"
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              block
              loading={loading}
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default LoginPage; 